# -*- coding: utf-8 -*-
from __future__ import with_statement
from fabric.api import *
from fabric.colors import *
import subprocess as sc
from fabric.contrib.console import confirm
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
env.hosts = ['localhost']
env.user="root"


def help():
    print(yellow("--------------classy-----------", bold=False));
    print(yellow("0.更新全量代码:", bold=False))
    print(yellow("1.classy代码:", bold=False))
    print(yellow("2.启动学科王爬虫(start)", bold=False))
    print(yellow("3.停止学科王爬虫(stop)", bold=False))
    print(yellow("4.执行xbj_toscrapypaper", bold=False))
    print(yellow("5.执行xbj_toscrapypaper", bold=False))

def start():
    help();
    print(red("请输入选项编号:"))
    text = raw_input()
    try:
        no=int(text)
    except Exception :
        no=0;
    if(no==0):
        pullshellmanage();
    elif(no==1):
        deploy();
    elif(no==2):
        scrapyxuekewang()
    elif(no==3):
        killxuekewang()
    elif (no == 4):
        logstash_paper()
    elif (no == 5):
        killlogstash_paper()
    else:
        pullshellmanage();
    start();


def logstash_paper():
    print("!开始执行同步脚本")
    os.chdir("/serv/xuekubao/xuekubao/spiders/logstash-config")
    out = sc.Popen("nohup logstash -f xbj_toscrapypaper.conf 2>&1 &", shell=True)
def killlogstash_paper():
    print("检测xbj_toscrapypaper进程存在!")
    kill_process_by_name('xbj_toscrapypaper');







#拉取管理最新代码
def pullshellmanage():
    print("更新shellmanage代码")
    os.chdir("/data/shellmanage/classyshell")
    sc.call('git pull',shell=True);
    print('更新scrapy代码!')
    os.chdir('/serv/xuekubao/xuekubao/')
    sc.call('git pull', shell=True);
    return;

def killxuekewang():
    print("检测scrapy crawl xuekewang进程存在!")
    kill_process_by_name('xuekewang');

#重新启动学科王爬虫
def scrapyxuekewang():
    print("检测scrapy crawl xuekewang进程存在!")
    kill_process_by_name('xuekewang');
    print("切换到/serv/xuekubao/xuekubao/spiders目录!")
    os.chdir("/serv/xuekubao/xuekubao/spiders")
    print("执行命令:nohup scrapy crawl xuekewang 2>&1 &")
    print(("日志文件目录:{}".format("/serv/scrapy/xuekepaper")))
    print("执行log日志:{}".format("/serv/scrapy/logs/xuekepaper.log"))
    out = sc.Popen("nohup scrapy crawl xuekewang 2>&1 &", shell=True,close_fds=True, stdout=sc.PIPE, stderr=sc.PIPE)

def deploy():
    print("检查classy进程是否存在!")
    kill_process_by_name('classy.jar')
    os.chdir("/serv/Classy")
    print("切换到master分支!")
    out = sc.check_call("git checkout master", shell=True, stdout=sc.PIPE, stderr=sc.PIPE)
    print("拉取master最新代码!")
    out = sc.check_call("git fetch --all&&git reset --hard origin/master", shell=True, stdout=sc.PIPE, stderr=sc.PIPE)
    print("maven编译最新代码！")
    out = sc.check_call("mvn clean install", shell=True, stdout=sc.PIPE, stderr=sc.PIPE)
    os.chdir("/serv/Classy/target")
    out = sc.check_call("chmod u+x classy.jar", shell=True, stdout=sc.PIPE, stderr=sc.PIPE)
    print("启动classy程序!")
    out = sc.Popen("java -jar classy.jar", shell=True, stdout=sc.PIPE, stderr=sc.PIPE)


def printprocess(name):
    print("%s",name)

def kill_process_by_name(name):
        cmd = "ps -ef | grep %s | grep -v grep | cut -c 9-15" % name
        f = os.popen(cmd)
        txt = f.readlines()
        if len(txt) == 0:
            print "不存在classy进程 \"%s\"!!" % name
            return
        else:
            for line in txt:
                colum = line.split()
                pid = colum[0]
                cmd = "kill -9 %d" % int(pid)
                rc = os.system(cmd)
                if rc == 0:
                    print "执行清除classy进程 \"%s\" 成功!!" % cmd
                else:
                    print "执行清除classy进程 \"%s\" 失败!!" % cmd
        return



